"""
门户网站 - 产品接口
"""
from typing import Optional
from fastapi import APIRouter, Depends, HTTPException, Query
from sqlalchemy.ext.asyncio import AsyncSession
from sqlalchemy import select, func

from app.dependencies import get_db
from app.schemas.common import ResponseModel, PaginatedResponse
from app.models.content import Product
from app.schemas.content import ProductResponse


router = APIRouter()


@router.get("", response_model=ResponseModel)
async def get_products(
    page: int = Query(1, ge=1),
    page_size: int = Query(12, ge=1, le=100),
    category_id: Optional[int] = Query(None),
    keyword: Optional[str] = Query(None),
    db: AsyncSession = Depends(get_db)
):
    """
    获取产品列表
    """
    query = select(Product).where(Product.status == 1)
    count_query = select(func.count(Product.id)).where(Product.status == 1)
    
    # 分类筛选
    if category_id:
        query = query.where(Product.category_id == category_id)
        count_query = count_query.where(Product.category_id == category_id)
    
    # 关键词搜索
    if keyword:
        query = query.where(Product.name.like(f"%{keyword}%"))
        count_query = count_query.where(Product.name.like(f"%{keyword}%"))
    
    # 排序和分页
    query = query.order_by(Product.sort_order.desc(), Product.created_at.desc())
    skip = (page - 1) * page_size
    query = query.offset(skip).limit(page_size)
    
    # 执行查询
    result = await db.execute(query)
    products = result.scalars().all()
    
    count_result = await db.execute(count_query)
    total = count_result.scalar_one()
    
    return ResponseModel(
        data=PaginatedResponse(
            total=total,
            page=page,
            page_size=page_size,
            items=[ProductResponse.model_validate(p) for p in products]
        )
    )


@router.get("/{product_id}", response_model=ResponseModel)
async def get_product(
    product_id: int,
    db: AsyncSession = Depends(get_db)
):
    """
    获取产品详情
    """
    result = await db.execute(
        select(Product).where(Product.id == product_id, Product.status == 1)
    )
    product = result.scalar_one_or_none()
    
    if not product:
        raise HTTPException(status_code=404, detail="产品不存在")
    
    # 更新浏览量
    product.view_count += 1
    await db.commit()
    await db.refresh(product)
    
    return ResponseModel(data=ProductResponse.model_validate(product))

